/**
 * Copyright (c) 2018-2028, Joffee.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sailmi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sailmi.common.controller.BaseController;
import com.sailmi.common.model.auth.AuthInfo;
import com.sailmi.common.mybatis.support.Condition;
import com.sailmi.common.mybatis.support.Query;
import com.sailmi.common.tool.api.R;
import com.sailmi.common.tool.utils.Func;
import com.sailmi.common.tool.utils.SecureUtil;
import com.sailmi.system.entity.ServiceEntity;
import com.sailmi.system.entity.SystemEntity;
import com.sailmi.system.service.IServiceService;
import com.sailmi.system.service.ISystemService;
import com.sailmi.system.entity.UserInfo;
import com.sailmi.system.service.IUserService;
import com.sailmi.system.vo.ServiceVO;
import com.sailmi.system.wrapper.ServiceWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 可提供的服务清单，企业可以通过服务清单 控制器
 *
 * @author sailmi
 * @since 2020-09-09
 */
@RestController
@RequestMapping("/service")
@Tag(name = "可提供的服务清单，企业可以通过服务清单", description = "可提供的服务清单，企业可以通过服务清单接口")
public class ServiceController extends BaseController {
	@Resource
	private IServiceService serviceService;
	@Resource
	private ISystemService systemService;
	@Resource
	private IUserService userService;


	/**
	* 详情
	*/
	@GetMapping("/detail")
	@Operation(summary = "详情", description = "传入service")
	public R<ServiceVO> detail(@ModelAttribute  ServiceEntity service) {
		ServiceEntity detail = serviceService.getOne(Condition.getQueryWrapper(service));
		return R.data(ServiceWrapper.build().entityVO(detail));
	}

	/**
	* 分页 可提供的服务清单，企业可以通过服务清单
	 * h后台管理员可以管理所有service，否则只是本公司的服务清单
	*/
	@GetMapping("/list")
	@Operation(summary = "分页", description = "传入service")
	public R<IPage<ServiceVO>> list(@ModelAttribute ServiceEntity service, @ModelAttribute Query query, HttpServletRequest request) {
		//获取该tenantId下的所有system，根据system查询所有service
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		ArrayList<Long> systemIds = new ArrayList<>();
		if(authInfo!=null && authInfo.getTenantId()!=null) {
			QueryWrapper<SystemEntity> systemEntityQueryWrapper = new QueryWrapper<>();
			if(authInfo.getTenantId().equals("000000")) {//平台管理员

			}else{
				systemEntityQueryWrapper.eq("tenant_id", authInfo.getTenantId());
			}
			List<SystemEntity> list = systemService.list(systemEntityQueryWrapper);
			if(list!=null && list.size()>0){
				list.stream().forEach(sysEntity->{
					systemIds.add(sysEntity.getId());
				});
			}
		}
		final QueryWrapper<ServiceEntity> queryWrapper = Condition.getQueryWrapper(service);
		IPage<ServiceEntity> pages = serviceService.page(Condition.getPage(query), queryWrapper);
		IPage<ServiceVO> serviceVOIPage = ServiceWrapper.build().pageVO(pages);
		if(serviceVOIPage!=null && serviceVOIPage.getTotal()>0){
			serviceVOIPage.getRecords().stream().forEach(serviceVO->{

				if(serviceVO.getServiceType()==0) {
					serviceVO.setServiceTypeName("公共授权");
				}else{
					serviceVO.setServiceTypeName("收费授权");
				}
				UserInfo userInfoR = userService.userInfo(serviceVO.getCreateUser());
				if(userInfoR!=null && userInfoR.getUser()!=null && userInfoR.getUser().getRealName()!=null) {
					serviceVO.setCreateName(userInfoR.getUser().getRealName());
				}
				UserInfo userInfoU = userService.userInfo(serviceVO.getUpdateUser());
				if(userInfoU!=null && userInfoU.getUser()!=null && userInfoU.getUser().getRealName()!=null) {
					serviceVO.setUpdateName(userInfoU.getUser().getRealName());
				}
			});
		}
		return R.data(serviceVOIPage);
	}


	/**
	 * 获取服务包树形结构
	 * AuthUser user
	 */
	@GetMapping("/service-tree")
	@Operation(summary = "服务包树形结构", description = "服务报树形结构")
	public R<List<ServiceVO>> grantTree() {
		return R.data(serviceService.grantTree());
	}



	/**
	* 自定义分页 可提供的服务清单，企业可以通过服务清单
	*/
	@GetMapping("/page")
	@Operation(summary = "分页", description = "传入service")
	public R<IPage<ServiceVO>> page(@ModelAttribute ServiceVO service,@ModelAttribute Query query) {
		IPage<ServiceVO> pages = serviceService.selectServicePage(Condition.getPage(query), service);
		return R.data(pages);
	}

	/**
	 * 获取服务包的菜单的分配树形结构
	 */
	@GetMapping("/service-tree-keys")
	@Operation(summary = "角色所分配的树", description = "角色所分配的树")
	public R<List<String>> serviceTreeKeys(@RequestParam(name="serviceId") String serviceId) {
		return R.data(serviceService.serviceTreeKeys(serviceId));
	}
	/**
	 * 设置菜单权限
	 *
	 * @param serviceId
	 * @param menuIds
	 * @return
	 */
	@PostMapping("/grant")
	@Operation(summary = "服务包菜单设置", description = "传入serviceId以及menuId集合")
	public R grantService(@Parameter(name = "roleId集合", required = true) @RequestParam(name="serviceId") String serviceId,
				   @Parameter(name = "menuId集合", required = true) @RequestParam(name="menuIds") String menuIds) {
		boolean temp = serviceService.grant(serviceId, Func.toLongList(menuIds));
		return R.status(temp);
	}



	/**
	* 新增 可提供的服务清单，企业可以通过服务清单
	*/
	@PostMapping("/save")
	@Operation(summary = "新增", description = "传入service")
	public R save(@Valid @RequestBody ServiceEntity service) {
		return R.status(serviceService.save(service));
	}

	/**
	* 修改 可提供的服务清单，企业可以通过服务清单
	*/
	@PostMapping("/update")
	@Operation(summary = "修改", description = "传入service")
	public R update(@Valid @RequestBody ServiceEntity service) {
		return R.status(serviceService.updateById(service));
	}

	/**
	* 新增或修改 可提供的服务清单，企业可以通过服务清单
	*/
	@PostMapping("/submit")
	@Operation(summary = "新增或修改", description = "传入service")
	public R submit(@Valid @RequestBody ServiceEntity service) {
		return R.status(serviceService.saveOrUpdate(service));
	}


	/**
	* 删除 可提供的服务清单，企业可以通过服务清单
	*/
	@PostMapping("/remove")
	@Operation(summary = "删除", description = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam(name="ids") String ids) {
		return R.status(serviceService.removeByIds(Func.toLongList(ids)));
	}


}
